package com.itsu.spbspider.controller;

import com.alibaba.fastjson.JSON;
import com.itsu.spbspider.entity.News;
import com.itsu.spbspider.exception.ApiException;
import com.itsu.spbspider.service.Crawler;
import com.itsu.spbspider.service.NewsService;
import com.itsu.spbspider.service.OrmData;
import com.itsu.spbspider.service.Parser;
import com.itsu.spbspider.service.impl.*;
import lombok.extern.slf4j.Slf4j;
import ognl.Ognl;
import ognl.OgnlException;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author suben
 * @create time 2020/2/9 13:55
 */
@RestController
@RequestMapping("/api")
@Slf4j
public class ApiController {

    @Resource
    private NewsService newsService;

    @Resource(name = "baiduNewsCrawlerDB")
    private Crawler crawler;

    @Resource
    private Parser parser;

    @Resource
    private OrmData ormData;

    @Resource(name = "baiduWeatherCrawlerWithCity")
    private Crawler baiduWeatherCrawlerWithCity;

    @Resource
    private BaiduWeatherParse baiduWeatherParse;

    @Resource
    private BudejieVideoCrawler budejieVideoCrawler;

    @Resource
    private BudejieVideoParse budejieVideoParse;

    @Resource
    private BudejieJokeCrawler budejieJokeCrawler;

    @Resource
    private BudejieJokeParse budejieJokeParse;

    @Resource
    private BaiduWeatherAreaCrawler baiduWeatherAreaCrawler;

    @Resource
    private BaiduWeatherAreaParse baiduWeatherAreaParse;

    @Resource
    private ToutiaoVideoCrawler toutiaoVideoCrawler;

    @GetMapping("/news")
    public Map getNews(@RequestParam("appkey") String appKey,
                       @RequestParam(value = "realTime", required = false) boolean realTime) throws Exception {
        Map map = new HashMap();
        List<News> newsList = null;
        String content = null;
        if (!realTime) {
            newsList = newsService.randomGetNews(appKey, 20);
        } else {
            content = crawler.crawlerData(8);
            newsList = parser.parseToObj(content);
            newsList.forEach(x -> {
                x.setJobId("123");
            });
            ormData.writeDataToDb(newsList);
        }
        if (!CollectionUtils.isEmpty(newsList)) {
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            for (News news : newsList) {
                if (StringUtils.isNotBlank(news.getTs()))
                    news.setTs(sf.format(Long.valueOf(news.getTs())));
            }
        }

        map.put("code", 0);
        map.put("data", newsList);
        map.put("hasmore", getHasMore(content));
        map.put("msg", "ok");
        return map;
    }

    boolean getHasMore(String content) throws OgnlException {
        if (StringUtils.isBlank(content)) {
            return false;
        }
        Map map = JSON.parseObject(content);
        String res = Ognl.getValue("data.hasmore", map).toString();
        return Boolean.valueOf(res).booleanValue();
    }


    @GetMapping("/weather")
    public Map getWeatherInfo(@RequestParam(value = "city", required = false) String city) throws Exception {
        if (StringUtils.isBlank(city)) {
            throw new ApiException(5001, "city值不能为null");
        }
        Map map = new HashMap();
        BaiduWeatherCrawlerWithCity baiduWeatherCrawlerWithCity = (BaiduWeatherCrawlerWithCity) this.baiduWeatherCrawlerWithCity;
        String content = baiduWeatherCrawlerWithCity.crawlerWeatherData(city);
        log.info("get baidu weather info : {}", content);
        Map dataMap = baiduWeatherParse.parseObj(content);
        if (MapUtils.isEmpty(dataMap)) {
            map.put("code", 1);
            map.put("msg", "暂无最新数据");
        } else {
            map.put("code", 0);
            map.put("data", dataMap);
        }
        return map;
    }

    @GetMapping("/video")
    public Map getVideo() throws Exception {
        Map map = new HashMap();
        String content = budejieVideoCrawler.crawlerData(11);
        Map data = budejieVideoParse.parseObj(content);
        if (MapUtils.isEmpty(data)) {
            map.put("code", 1);
            map.put("msg", "暂无最新数据");
        } else {
            map.put("code", 0);
            map.put("data", data);
        }
        return map;
    }

    @GetMapping("/toutiao/video")
    public Map getTouTiaoVideo() throws Exception {
        Map map = toutiaoVideoCrawler.crawlerData();
        map.put("code", 0);
        return map;
    }

    @GetMapping("/joke")
    public Map getJoke() throws Exception {

        String content = budejieJokeCrawler.crawlerData(12);
        Map map = budejieJokeParse.parseObj(content);
        if (MapUtils.isEmpty(map) || map.get("data") == null) {
            map.put("code", 1);
            map.put("msg", "暂无最新数据");
        } else {
            map.put("code", 0);
        }
        return map;
    }

    @GetMapping("/area/{id}")
    public Map getArea(@PathVariable("id") String id) throws Exception {
        if (StringUtils.isBlank(id)) {
            throw new ApiException(5001, "id is null");
        }
        baiduWeatherAreaCrawler.setId(id);
        String content = baiduWeatherAreaCrawler.crawlerData(13);
        Map map = baiduWeatherAreaParse.parseObj(content);
        map.put("code", 0);
        return map;
    }
}
